<?php

    class Application_Plugin_SetApp extends Zend_Controller_Plugin_Abstract
    {

        protected $_pageArray = array(); //list of controllers and action which can be accessed without login

        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            $db = Zend_Db_Table::getDefaultAdapter();

            if ($_SERVER["REMOTE_ADDR"] == "127.0.0.1")
            {
                date_default_timezone_set("Asia/Kolkata");
                $db->query("SET SESSION time_zone = '+5:30'");
            }
            else
            {
                date_default_timezone_set("America/New_York");
                $db->query("SET SESSION time_zone = '-5:00'");
            }
            
            $this->setSiteConstants();
            $module = $request->getModuleName();

            $this->restoreEventIfSpotBecomesEmpty();
            $this->markEventInactiveAfterSpotsFilled();

            if ($module == 'default')
            {
                //To set the default Database
                $this->_name = 'quickties';

                $controller = $request->getControllerName();
                $action = $request->getActionName();
                $path = $controller . "/" . $action;

                $x = new Zend_Auth_Storage_Session('User_Auth');
                $y = $x->read();

//                prd($_COOKIE);
                if ($path != "index/logout")
                {
                    if (isset($_COOKIE["front_cookie"]) && empty($y))
                    {
                        $cookie_value = trim($_COOKIE["front_cookie"]);
                        $db = Zend_Db_Table::getDefaultAdapter();
                        $sql = "SELECT cookie_user_id, cookie_expire_time FROM " . TABLE_COOKIES . " WHERE cookie_value = '" . $cookie_value . "' and cookie_module = '" . $module . "'";
                        $result = $db->query($sql)->fetch();

                        if (!empty($result) && $result["cookie_expire_time"] >= time())
                        {
                            $authAdapter = new Zend_Auth_Adapter_DbTable($db);

                            $authAdapter->setTableName(TABLE_USERS)
                                    ->setIdentityColumn('user_id')
                                    ->setCredentialColumn('user_id');

                            $authAdapter->setIdentity($result["cookie_user_id"])
                                    ->setCredential($result["cookie_user_id"]);

                            $zend_auth = Zend_Auth::getInstance();
                            $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                            $result = $zend_auth->authenticate($authAdapter);
                            $user = $authAdapter->getResultRowObject(null, 'user_password');
                            $zend_auth->getStorage()->write($user);
                            $this->getResponse()->setRedirect(APPLICATION_URL . "/profile");
                        }
                    }
                }

                //To set Page Title
                $view = new Zend_View();
            }
            elseif ($module == 'admin')
            {
                $controller = $request->getControllerName();
                $action = $request->getActionName();
                $path = $controller . "/" . $action;

                $x = new Zend_Auth_Storage_Session('Admin_Auth');
                $y = $x->read();

                $admin_controller = $request->getControllerName();
                $admin_action = $request->getActionName();
                $chkPath = $module . "/" . $admin_controller . "/" . $admin_action;

                if ($chkPath != "admin/index/index")
                {
                    if (empty($y))
                    {
                        $r = new Zend_Controller_Action_Helper_Redirector();
                        $r->gotoUrl('/admin')->redirectAndExit();
                        die;
                    }
                }

//                prd($_COOKIE);
                if ($path != "index/logout")
                {
                    if (isset($_COOKIE["admin_cookie"]) && empty($y))
                    {
                        $cookie_value = trim($_COOKIE["admin_cookie"]);
                        $db = Zend_Db_Table::getDefaultAdapter();
                        $sql = "SELECT cookie_user_id, cookie_expire_time FROM " . TABLE_COOKIES . " WHERE cookie_value = '" . $cookie_value . "' and cookie_module = '" . $module . "'";
                        $result = $db->query($sql)->fetch();

                        if (!empty($result) && $result["cookie_expire_time"] >= time())
                        {
                            $authAdapter = new Zend_Auth_Adapter_DbTable($db);

                            $authAdapter->setTableName(TABLE_ADMIN)
                                    ->setIdentityColumn('admin_id')
                                    ->setCredentialColumn('admin_id');

                            $authAdapter->setIdentity($result["cookie_user_id"])
                                    ->setCredential($result["cookie_user_id"]);

                            $zend_auth = Zend_Auth::getInstance();
                            $zend_auth->setStorage(new Zend_Auth_Storage_Session('Admin_Auth'));
                            $result = $zend_auth->authenticate($authAdapter);
                            $user = $authAdapter->getResultRowObject(null, 'admin_password');
                            $zend_auth->getStorage()->write($user);
                            $this->getResponse()->setRedirect(ADMIN_APPLICATION_URL . "/index/dashboard");
                        }
                    }
                }
                else
                {
                    if (empty($y) && $path != "index/index")
                    {
                        $_SESSION["messageError"] = "Please login first";
                        $this->getResponse()->setRedirect(ADMIN_APPLICATION_URL);
                    }
                    elseif (!empty($y) && $path == "index/index")
                    {
                        $this->getResponse()->setRedirect(ADMIN_APPLICATION_URL . "/index/dashboard");
                    }
                }

                $layoutPath = APPLICATION_PATH . "/layouts/admin/";
                $layout = Zend_Layout::getMvcInstance();
                $layout->setLayout("layout");
                $layout->setLayoutPath($layoutPath);

                $this->_name = 'quickties';
            }
        }

        public function postDispatch(Zend_Controller_Request_Abstract $request)
        {

            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT cookie_id FROM " . TABLE_COOKIES . " WHERE cookie_expire_time < '" . time() . "'";
            $result = $db->query($sql)->fetchAll();
            if (!empty($result))
            {
                foreach ($result as $key => $value)
                {
                    $cookie_id = $value["cookie_id"];
                    $del_sql = "DELETE FROM " . TABLE_COOKIES . " WHERE cookie_id = $cookie_id";
                    $db->query($del_sql);
                }
            }

            $this->markEventInactiveAfterEndDate();
        }

        public function setSiteConstants()
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT config_key, config_value FROM " . TABLE_CONFIG . " WHERE `config_type` = 'SITE_CONFIG'";
            $result = $db->query($sql)->fetchAll();
//            prd($result);
            foreach ($result as $key => $value)
            {
                define(strtoupper($value["config_key"]), $value["config_value"]);
            }
        }

        public function eventEndSendEmailToCreator($event_id)
        {
            if (!empty($event_id))
            {
                $email_model = new Application_Model_Email();
                $db = Zend_Db_Table::getDefaultAdapter();
                $sql = "SELECT user_first_name, user_last_name, user_email, event_title FROM " . TABLE_EVENTS . " INNER JOIN " . TABLE_USERS . " ON event_created_by=user_id WHERE event_id = $event_id";
                $result = $db->query($sql)->fetch();

                $event_title = $result["event_title"];
                $creator_full_name = $result["user_first_name"] . " " . $result["user_last_name"];
                $creator_email = $result["user_email"];

                $email_sql = "SELECT et_subject, et_content FROM " . TABLE_EMAIL_TEMPLATES . " WHERE et_key = 'event_end_email_to_creator'";
                $email_record = $db->query($email_sql)->fetch();
                $email_subject = trim($email_record["et_subject"]);
                $et_content = trim($email_record["et_content"]);

                $attending_sql = "SELECT user_first_name, user_last_name FROM " . TABLE_EVENT_JOIN . " INNER JOIN " . TABLE_USERS . " ON ej_user_id = user_id WHERE ej_event_id = $event_id";
                $attending_records = $db->query($attending_sql)->fetchAll();

                $new_array = array();
                foreach ($attending_records as $key => $value)
                {
                    $attending_full_name = $value["user_first_name"] . " " . $value["user_last_name"];

                    $new_array[] = $attending_full_name;
                }

                $messageContent = str_replace("{event_title}", $event_title, $et_content);
                $messageContent = str_replace("{event_creator_name}", $creator_full_name, $messageContent);
                $messageContent = str_replace("{full_name}", explode("<br/>", $new_array), $messageContent);

                if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1")
                    $email_model->sendMail($creator_email, SITE_EMAIL, SITE_NAME, $email_subject, $messageContent);
            }
        }

//        public function eventEndSendMailToAttendees()
//        {
//            $db = Zend_Db_Table::getDefaultAdapter();
//            $sql = "SELECT event_id, event_end_date FROM " . TABLE_EVENTS . " WHERE event_ended = '0'";
//            $result = $db->query($sql)->fetchAll();
//
//            foreach ($result as $key => $value)
//            {
//                $event_id = $value["event_id"];
//                $event_end_date_array = json_decode($value["event_end_date"]);
//
//                $current_date = date("d M Y");
//                $event_end_date = $event_end_date_array->day[0] . " " . date("F", strtotime($event_end_date_array->month[0])) . " " . $event_end_date_array->year[0];
//                if (strcmp($current_date, $event_end_date) == 0 || strtotime($event_end_date) < time())
//                {
////                    pr("event end date - ".strtotime($event_end_date));
////                    prd("time - ".time());
//                    $email_model = new Application_Model_Email();
//
//                    $email_sql = "SELECT et_subject, et_content FROM " . TABLE_EMAIL_TEMPLATES . " WHERE et_key = 'event_end_email_to_attendees'";
//                    $email_record = $db->query($email_sql)->fetch();
//
//                    $email_subject = trim($email_record["et_subject"]);
//                    $email_content = stripslashes(trim($email_record["et_content"]));
//
//                    $attending_sql = "SELECT user_first_name, user_last_name, user_email, event_title FROM " . TABLE_USERS . " 
//                                                    INNER JOIN " . TABLE_EVENT_JOIN . " ON user_id = ej_user_id 
//                                                        INNER JOIN " . TABLE_EVENTS . " ON event_id = ej_event_id 
//                                                            WHERE ej_event_id = $event_id";
//                    $attending_records = $db->query($attending_sql)->fetchAll();
//
//                    foreach ($attending_records as $a_key => $a_value)
//                    {
//                        $event_title = $a_value["event_title"];
//                        $full_name = $a_value["user_first_name"] . " " . $a_value["user_last_name"];
//                        $user_email = trim($a_value["user_email"]);
//
//                        $message = str_replace("{user_name}", $full_name, $email_content);
//                        $message = str_replace("{event_title}", $event_title, $message);
//
//                        if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1")
//                            $email_model->sendMail($user_email, SITE_EMAIL, SITE_NAME, $email_subject, $message);
//                    }
//
//                    $this->eventEndSendEmailToCreator($event_id);
//
//                    $tmp_sql = "UPDATE " . TABLE_EVENTS . " SET event_ended='1' WHERE event_id = $event_id";
//                    $db->query($tmp_sql);
//                }
//            }
//        }

        public function markEventInactiveAfterEndDate() //yaha sab sahi h
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT event_id, event_end_date FROM " . TABLE_EVENTS . " WHERE event_active = '1' ORDER BY event_id ASC";
            $result = $db->query($sql)->fetchAll();
//            prd($result);
            $email_model = new Application_Model_Email();

            $email_sql = "SELECT et_subject, et_content FROM " . TABLE_EMAIL_TEMPLATES . " WHERE et_key = 'event_end_email_to_attendees'";
            $email_record = $db->query($email_sql)->fetch();

            $email_subject = trim($email_record["et_subject"]);
            $email_content = stripslashes(trim($email_record["et_content"]));

            foreach ($result as $key => $value)
            {
                $event_id = $value["event_id"];
//                $event_end_date_array = json_decode($value["event_end_date"]);
//                $event_end_date = strtotime($event_end_date_array->day[0] . " " . date("F", strtotime($event_end_date_array->month[0])) . " " . $event_end_date_array->year[0]);
                $event_end_date = getEventDate($value["event_end_date"]);
                $new_event_end_date = date("d-M-Y", strtotime($event_end_date . ' + 1 day'));

                if (strtotime($new_event_end_date) < time())
                {
//                    $tmp_sql = "UPDATE " . TABLE_EVENTS . " SET event_active = '0' WHERE event_id = $event_id";
                    $tmp_sql = "UPDATE " . TABLE_EVENTS . " SET event_active = '0', event_ended = '1' WHERE event_id = $event_id";
                    $result = $db->query($tmp_sql);

                    $attending_sql = "SELECT user_first_name, user_last_name, user_email, event_title FROM " . TABLE_USERS . " 
                                                    INNER JOIN " . TABLE_EVENT_JOIN . " ON user_id = ej_user_id 
                                                        INNER JOIN " . TABLE_EVENTS . " ON event_id = ej_event_id 
                                                            WHERE ej_event_id = $event_id AND ej_is_accepted = '1' AND ej_is_invited = '0'";
                    $attending_records = $db->query($attending_sql)->fetchAll();

                    foreach ($attending_records as $a_key => $a_value)
                    {
                        $event_title = $a_value["event_title"];
                        $full_name = $a_value["user_first_name"] . " " . $a_value["user_last_name"];
                        $user_email = trim($a_value["user_email"]);

                        $message = str_replace("{user_name}", $full_name, $email_content);
                        $message = str_replace("{event_title}", $event_title, $message);

                        if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1")
                            $email_model->sendMail($user_email, SITE_EMAIL, SITE_NAME, $email_subject, $message);
                    }
                    $this->eventEndSendEmailToCreator($event_id);
                }
            }
        }

        public function markEventInactiveAfterSpotsFilled()
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT event_id, event_group_size FROM " . TABLE_EVENTS . " WHERE event_active = '1' AND event_group_type = 'limited'";
            $result = $db->query($sql)->fetchAll();

            foreach ($result as $key => $value)
            {
                $event_id = $value["event_id"];
                $event_group_size = $value["event_group_size"];

                $join_count_sql = "SELECT COUNT(ej_id) as totalcount FROM " . TABLE_EVENT_JOIN . " WHERE ej_event_id = $event_id AND ej_is_accepted = '1' AND ej_is_invited = '0'";
                $join_count_records = $db->query($join_count_sql)->fetch();
                $totaljoins = $join_count_records["totalcount"];

                if ($totaljoins >= $event_group_size)
                {
                    $tmp_sql = "UPDATE " . TABLE_EVENTS . " SET event_active = '0' WHERE event_id = $event_id";
                    if (!$db->query($tmp_sql))
                    {
                        echo 'An error occured';
                        die;
                    }
                }
            }
        }

        public function restoreEventIfSpotBecomesEmpty()
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT event_id, event_group_size, event_end_date FROM " . TABLE_EVENTS . " 
                            WHERE event_active = '0' AND event_ended = '0' AND event_celebrity_event='0' AND event_group_type = 'limited'";
            $result = $db->query($sql)->fetchAll();

            foreach ($result as $key => $value)
            {
                $event_id = $value["event_id"];
                $event_group_size = $value["event_group_size"];
                $event_date_array = $value["event_end_date"];
                $event_end_date = getEventDate($event_date_array);
//                $new_event_end_date = date("d-M-Y", strtotime($event_end_date));

                $tmpsql = "SELECT COUNT(ej_id) as totaljoins FROM " . TABLE_EVENT_JOIN . " WHERE ej_event_id=$event_id AND ej_is_accepted = '1' AND ej_is_invited = '0'";
                $tmpresult = $db->query($tmpsql)->fetch();

                $totaljoins = $tmpresult["totaljoins"];

//                pr(strtotime($event_end_date) ." --- ". time());
//                if (($totaljoins < $event_group_size) && (strtotime($event_end_date) > time()))
                if (($totaljoins < $event_group_size))
                {
                    $tmp_sql = "UPDATE " . TABLE_EVENTS . " SET event_active = '1' WHERE event_id = $event_id";
                    if (!$db->query($tmp_sql))
                    {
                        echo 'An error occured';
                        die;
                    }
                }
            }
        }

//
//        public function restoreEventIfSpotBecomesEmpty()
//        {
//            $db = Zend_Db_Table::getDefaultAdapter();
//            $sql = "SELECT COUNT(ej_id) as totaljoins, event_group_size, event_id, event_end_date FROM " . TABLE_EVENTS . " AS e 
//                            LEFT JOIN " . TABLE_EVENT_JOIN . " AS ej ON e.event_id = ej.ej_event_id
//                                WHERE e.event_active = '0' AND ej.ej_is_accepted = '1' AND ej.ej_id IS NOT NULL
//                                    GROUP BY e.event_id";
//            $result = $db->query($sql)->fetchAll();
//            prd($result);
//
//            foreach ($result as $key => $value)
//            {
//                $event_id = $value["event_id"];
//                $event_group_size = $value["event_group_size"];
//                $totaljoins = $value["totaljoins"];
//                $event_date_array = $value["event_end_date"];
//                $event_date = getEventDate($event_date_array);
//
//                if (($totaljoins < $event_group_size) && (strtotime($event_date) > time()))
//                {
//                    $tmp_sql = "UPDATE " . TABLE_EVENTS . " SET event_active = '1' WHERE event_id = $event_id";
//                    $result = $db->query($tmp_sql);
//                }
//            }
//        }     

        public function checkIfEventJoined($friend_id, $event_id)
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT ej_id FROM " . TABLE_EVENT_JOIN . " WHERE ej_user_id = $friend_id AND ej_event_id = $event_id AND ej_is_invited = '1'";
//            prd($sql);
            $result = $db->query($sql)->fetchAll();

            $returnValue = FALSE;
            if (!empty($result))
                $returnValue = TRUE;

            return $returnValue;
        }

        public function checkIfEventAccepted($friend_id, $event_id)
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $sql = "SELECT ej_id FROM " . TABLE_EVENT_JOIN . " WHERE ej_user_id = '$friend_id' AND ej_event_id = '$event_id' AND ej_is_accepted = '1'";
//            prd($sql);
            $result = $db->query($sql)->fetch();
//            prd($result);

            $returnValue = FALSE;
            if (!empty($result))
                $returnValue = TRUE;

            return $returnValue;
        }

    }